﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Providers
{
	public class ShopzillaExport : ExportBase
	{
		private List<Models.ShopzillaProductInfo> m_Document;

		public ShopzillaExport()
		{

		}

		public override void InitializeSettings(Models.Settings settings)
		{
			settings.FileName = "shopzilla.txt";
		}

		public override string Name
		{
			get { return "shopzilla"; }
		}

		public override string LeadSourceId
		{
			get { return "b20efdc9-35bc-416d-9a3e-da3d7565a499"; }
		}

		public override void CreateDocument()
		{
			m_Document = new List<Models.ShopzillaProductInfo>();
		}

		public override void AddElementToDocument(ERPStore.Models.Product product, ERPStore.Models.ProductStockInfo productStockInfo)
		{
			var productInfo = new Models.ShopzillaProductInfo();

			productInfo.Category = GetShopzillaCategory(product.Category);
			if (product.Brand != null)
			{
				productInfo.Brand = product.Brand.Name;
			}
			productInfo.Title = product.PageTitle ?? product.Title;
			productInfo.Description = product.ShortDescription ?? product.LongDescription ?? product.Title;
			productInfo.Description = productInfo.Description.Left(1000);
			productInfo.Description = productInfo.Description.Replace("\r\n", "");
			// var urlBuilder = new ERPStore.Exporter.ProductUrlBuilder();
			productInfo.Link = BuildEncryptedProductUrl(LeadSource, product);
			// urlBuilder.GetProductUrl(leadSource, product); // string.Format("http://{0}/produit/{1}/{2}/?estid=shopzilla&utm_source=shopzilla&estcd={3:yyMMdd}", GlobalConfiguration.Configuration.Settings.DefaultUrl, product.EncodedCode(), product.EncodedLink(), DateTime.Now);
			if (product.DefaultImage != null)
			{
				productInfo.PictureUrl = string.Format("http://{0}{1}", GlobalConfiguration.Configuration.Settings.DefaultUrl, string.Format(product.DefaultImage.Url, 0, 0));
			}
			productInfo.SKU = product.Code;

			string stockValue = null;
			if (productStockInfo != null)
			{
				if (productStockInfo.HasStock)
				{
					stockValue = "En Stock";
					productInfo.SpecialOffer = "3";
				}
				else if (productStockInfo.ProvisionnedQuantity > 0)
				{
					stockValue = "Commandé en attente de livraison";
				}
				else
				{
					stockValue = "Stock épuisé";
				}
			}
			else
			{
				stockValue = "Voir le site";
			}
			productInfo.Inventory = stockValue;
			productInfo.Condition = "Neuf";
			var miniFee = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList[0].MinimalFreeOfCarriageAmount;
			var deliveryFee = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList[0].ShippingFeeAmount;
			if (product.SalePrice.Value > miniFee)
			{
				productInfo.DeliveryFee = "0";
			}
			else
			{
				productInfo.DeliveryFee = string.Format("{0:F2}", deliveryFee);
			}

			//if (product.PromotionalPrice != null)
			//{
			//    productInfo.SpecialOffer += " 7";
			//}
			productInfo.SpecialOffer = productInfo.SpecialOffer.Replace("  ", " ");
			if (!product.Gtin.EAN.IsNullOrTrimmedEmpty())
			{
				productInfo.EAN = product.Gtin.EAN;
			}
			else if (!product.Gtin.UPC.IsNullOrTrimmedEmpty())
			{
				productInfo.EAN = product.Gtin.UPC;
			}

			var cultureInfo = new System.Globalization.CultureInfo("en-US");
			cultureInfo.NumberFormat.NumberDecimalDigits = '.';
			cultureInfo.NumberFormat.NumberGroupSeparator = "";
			productInfo.SalePrice = product.BestPrice.ValueWithTax.ToString("F2", cultureInfo);

			m_Document.Add(productInfo);
		}

		public override void SaveDocument()
		{
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var fileName = System.IO.Path.Combine(path, Settings.FileName);

			if (System.IO.File.Exists(fileName))
			{
				System.IO.File.Delete(fileName);
			}

			var headerLine = Services.ShopzillaSerializer<Models.ShopzillaProductInfo>.GetHeader(separator: "\t");

			using (var s = System.IO.File.CreateText(fileName))
			{
				s.WriteLine(headerLine);
				foreach (var item in m_Document)
				{
					var line = Services.ShopzillaSerializer<Models.ShopzillaProductInfo>.Serialize(item, separator: "\t");
					s.WriteLine(line);
				}

				s.Flush();
			}
			
		}

		public override void Dispose()
		{
			
		}

		private string GetShopzillaCategory(ERPStore.Models.ProductCategory category)
		{
			if (category == null)
			{
				return null;
			}
			if (category.ExtendedProperties == null)
			{
				return GetShopzillaCategory(category.Parent);
			}
			if (!category.ExtendedProperties.Any(i => i.Key.Name == "ShopzillaProductCategory"))
			{
				return GetShopzillaCategory(category.Parent);
			}

			return category.ExtendedProperties["ShopzillaProductCategory"]["ShopzillaMappedCategoryName"];
		}

	}
}
